<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <span style="margin-left: 20px">{{
        isTanma
          ? formatDate(new Date(nextDate), "yyyy/MM/dd")
          : list1.length
          ? formatDate(new Date(list1[0].day * 1000), "yyyy/MM/dd")
          : "获取失败"
      }}</span>
      <span style="margin-left: 20px; font-size: 14px; color: #409eff">{{
        fileName
      }}</span>

      <el-button
        size="mini"
        class="btn-add"
        @click="clearFilter"
        style="margin-left: 20px"
        >清除所有过滤</el-button
      >
      <el-button
        size="mini"
        class="btn-add"
        @click="lookErrorList"
        style="margin-left: 20px"
        >查看错误列表({{ this.errorList.length }}个)</el-button
      >
    </el-card>
    <div class="table-container">
      <el-tabs type="border-card" v-model="tabsId" width="100%">
        <el-tab-pane label="上午单" name="0">
          <!-- 客户列表 -->
          <el-table
            ref="clientTable1"
            :data="clientAM"
            style="width: 46%; margin-right: 10px"
            v-loading="celientListLoading"
            @selection-change="filterClient"
            :default-sort="{ prop: 'time', order: 'ascending' }"
            border
          >
            <el-table-column
              :label="'客户列表（' + clientAMLength + '）'"
              align="center"
            >
              <el-table-column
                type="selection"
                width="60"
                align="center"
                fixed
              ></el-table-column>
              <el-table-column label="公司名称" width="150" align="center">
                <template slot-scope="scope">
                  <p>{{ scope.row.companyName }}</p>
                  <p
                    style="color: red"
                    v-if="
                      scope.row.abandonedPerson != null &&
                      0 != scope.row.abandonedPerson.length
                    "
                  >
                    放弃人：{{ scope.row.abandonedPerson }}
                  </p>
                </template>
              </el-table-column>
              <el-table-column
                label="时间"
                align="center"
                prop="time"
                sortable
                width="100"
              >
                <template slot-scope="scope">
                  <p>{{ scope.row.time }}</p>
                </template>
              </el-table-column>
              <el-table-column
                label="类型"
                align="center"
                prop="type"
                :filters="clientType"
                :filter-method="postFilter"
                width="100"
              >
                <template slot-scope="scope">
                  <p>{{ clientType[scope.row.type].text }}</p>
                </template>
              </el-table-column>

              <el-table-column label="地址" align="left">
                <template slot-scope="scope">
                  <div style="display: flex; align-items: center">
                    <el-tag
                      type="danger"
                      style="margin-left: 5px; margin-right: 10px"
                      v-if="scope.row.adressStatus === 1"
                      >错误</el-tag
                    >
                    <div>{{ scope.row.companyAddress }}</div>
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column label="出单人" width="100" align="center">
                <template slot-scope="scope">
                  <p>{{ scope.row.seller }}</p>
                </template>
              </el-table-column> -->
              <el-table-column label="指派人员" width="100" align="center">
                <template slot-scope="scope">
                  <p>{{ scope.row.userName }}</p>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>

          <!-- 员工列表 -->
          <el-table
            ref="staffTable1"
            :data="list3"
            style="width: 46%; margin-left: 10px"
            @selection-change="change1"
            v-loading="staffListLoading"
            border
            show-overflow-tooltip
          >
            <el-table-column
              :label="'员工列表（' + list3.length + '）'"
              align="center"
            >
              <el-table-column
                type="selection"
                width="60"
                align="center"
                fixed
              ></el-table-column>
              <!-- <el-table-column label="编号" width="65" align="center">
                <template slot-scope="scope">{{ scope.row.id }}</template>
              </el-table-column> -->
              <el-table-column label="姓名" align="center">
                <template slot-scope="scope">
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    "
                  >
                    <el-tag
                      type="warning"
                      style="margin-left: 5px; margin-right: 10px"
                      :style="{
                        visibility:
                          scope.row.newPeople === 1 ? 'visible' : 'hidden',
                      }"
                      >新人</el-tag
                    >
                    <div>{{ scope.row.staffName }}</div>
                    <div></div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="地区" align="center" prop="areaId">
                <template slot-scope="scope">
                  <p>{{ scope.row.cityName || scope.row.areaName || "" }}</p>
                </template>
              </el-table-column>
              <el-table-column
                label="职责"
                align="center"
                prop="post"
                :filters="[
                  { text: '前道', value: 0 },
                  { text: '后道', value: 1 },
                ]"
                :filter-method="postFilter1"
              >
                <template slot-scope="scope">
                  <p>{{ clientType[scope.row.post].text }}</p>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <div class="btn btn-container-del" v-if="tabsId == '0'">
          <el-button size="mini" class="el-button--danger" @click="deleteClient"
            >删除客户</el-button
          >
        </div>

        <el-tab-pane label="下午单" name="1">
          <!-- 客户列表 -->
          <el-table
            ref="clientTable2"
            :data="clientPM"
            style="width: 46%; margin-right: 10px"
            v-loading="celientListLoading"
            @selection-change="filterSecond"
            :default-sort="{ prop: 'time', order: 'ascending' }"
            border
          >
            <el-table-column
              :label="'客户列表（' + clientPMLength + '）'"
              align="center"
            >
              <el-table-column
                type="selection"
                width="60"
                align="center"
                fixed
              ></el-table-column>
              <el-table-column label="公司名称" width="150" align="center">
                <template slot-scope="scope">
                  <p>{{ scope.row.companyName }}</p>
                  <p
                    v-if="
                      scope.row.abandonedPerson != null &&
                      0 != scope.row.abandonedPerson.length
                    "
                    style="color: red"
                  >
                    放弃人：{{ scope.row.abandonedPerson }}
                  </p>
                </template>
              </el-table-column>
              <el-table-column
                label="时间"
                align="center"
                prop="time"
                sortable
                width="100"
              >
                <template slot-scope="scope">
                  <p>{{ scope.row.time }}</p>
                </template>
              </el-table-column>
              <el-table-column
                label="类型"
                align="center"
                prop="type"
                :filters="clientType"
                :filter-method="postFilter"
                width="100"
              >
                <template slot-scope="scope">
                  <p>{{ clientType[scope.row.type].text }}</p>
                </template>
              </el-table-column>

              <el-table-column label="地址" align="left">
                <template slot-scope="scope">
                  <div style="display: flex; align-items: center">
                    <el-tag
                      type="danger"
                      style="margin-left: 5px; margin-right: 10px"
                      v-if="scope.row.adressStatus === 1"
                      >错误</el-tag
                    >
                    <div>{{ scope.row.companyAddress }}</div>
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column label="出单人" width="100" align="center">
                <template slot-scope="scope">
                  <p>{{ scope.row.seller }}</p>
                </template>
              </el-table-column> -->
              <el-table-column label="指派人员" width="100" align="center">
                <template slot-scope="scope">
                  <p>{{ scope.row.userName }}</p>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>

          <!-- 员工列表 -->
          <el-table
            ref="staffTable2"
            :data="list4"
            style="width: 46%; margin-left: 10px"
            @selection-change="change2"
            v-loading="staffListLoading"
            border
            show-overflow-tooltip
          >
            <el-table-column
              :label="'员工列表（' + list4.length + '）'"
              align="center"
            >
              <el-table-column
                type="selection"
                width="60"
                align="center"
                fixed
              ></el-table-column>
              <!-- <el-table-column label="编号" width="65" align="center">
                <template slot-scope="scope">{{ scope.row.id }}</template>
              </el-table-column> -->
              <el-table-column label="姓名" align="center">
                <template slot-scope="scope">
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    "
                  >
                    <el-tag
                      type="warning"
                      style="margin-left: 5px; margin-right: 10px"
                      :style="{
                        visibility:
                          scope.row.newPeople === 1 ? 'visible' : 'hidden',
                      }"
                      >新人</el-tag
                    >
                    <div>{{ scope.row.staffName }}</div>
                    <div></div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="地区" align="center" prop="areaId">
                <template slot-scope="scope">
                  <p>{{ scope.row.cityName || scope.row.areaName || "" }}</p>
                </template>
              </el-table-column>
              <el-table-column
                label="职责"
                align="center"
                prop="post"
                :filters="[
                  { text: '前道', value: 0 },
                  { text: '后道', value: 1 },
                ]"
                :filter-method="postFilter1"
              >
                <template slot-scope="scope">
                  <p>{{ clientType[scope.row.post].text  }}</p>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <div class="btn btn-container-del" v-if="tabsId == '1'">
          <el-button
            size="mini"
            class="el-button--danger"
            @click="deleteClientByAfternoon"
            >删除客户</el-button
          >
        </div>
      </el-tabs>
    </div>
    <el-dialog
      :visible.sync="showErrorClient"
      :close="closeErrorPage"
      title="错误列表"
    >
      <errorClientList key="errorData" :errorList="errorList"></errorClientList>
    </el-dialog>

    <div class="btn-container">
      <el-button
        type="primary"
        :loading="btnLoading"
        class="btn"
        @click.stop="getGenreateResult"
        >生成结果
        <span v-if="btnLoading && countdown > 0">{{
          countdown + "s"
        }}</span></el-button
      >
    </div>
  </div>
</template>
<script>
import {
  updateDeleteStatus,
  updateNewStatus,
  updateRecommendStatus,
  updateHot,
} from "../../../api/product";

import { FormatCreateTime } from "../../../filter/time";

import {
  OPERATION_STATUS_ARRAY,
  PUBLISH_STATUS_OPTIONS,
  CLIENT_TYPE,
  WAIT_TIME
} from "../../../contanst/data";
import { listBySearch, mint, updateStatus } from "../../../api/cert";
import { Storage } from "../../../store/storage";
import { handleCurrentChange, handleSizeChange } from "../../../page/page";
import { DefaultListQuery } from "../../../entity/market";
import { handleSelectionChange } from "../../../checkbox/handler";
import { Message } from "element-ui";
import { formatDate } from "@/utils/date";

import { clientList, getErrorListByRequest, removeClient } from "../../../api/dispatch";
import { getArea, staffListSearch } from "../../../api/staff";
import { mapState } from "vuex";
import { genreateResult } from "../../../api/dispatch";
import { maxNum } from "@/utils/max";
export default {
  name: "productList",
  data() {
    return {
      showErrorClient: false,
      tabsId: "0",
      fileName: "",
      formatDate,
      fliterVisit: [],
      fliterVisitSecond: [],
      editSkuInfo: {
        dialogVisible: false,
        productId: null,
        productSn: "",
        productAttributeCategoryId: null,
        stockList: [],
        productAttr: [],
        keyword: null,
      },
      clientType: CLIENT_TYPE,
      operates: OPERATION_STATUS_ARRAY,
      operateType: null,
      listQuery: Object.assign({}, DefaultListQuery),
      list: [],
      nftTypeId: 0,
      searchTreeProps: {},
      total: 0,
      size: 15,
      currentNftType: "",
      listLoading: true,
      dialogVisible: false,
      selectProductCateValue: null,
      multipleSelection: [],
      productCateOptions: [],
      brandOptions: [],
      publishStatusOptions: PUBLISH_STATUS_OPTIONS,
      list1: [],
      clientAM: [],
      clientAMLength: 0,
      clientPMLength: 0,
      clientPM: [],
      list2: [],
      list3: [],
      list4: [],
      clientParams: {
        pageNum: 1,
        total: 0,
        pageSize: null,
      },
      staffParams: {
        pageNum: 1,
        total: 0,
        pageSize: null,
        lastId: 0,
      },
      celientListLoading: true,
      staffListLoading: true,
      submitParams: {
        ids: [],
        afternoons: [],
      },
      btnLoading: false,
      countdown: 0,
      timer: null,
      interval: null,
      nextDate: new Date(),
    };
  },

  components: {
    errorClientList: () => import("./component/errorList.vue"),
  },

  created() {
    console.log(this.errorList);
    const { fileName, time } = this.$route.query;
    if (fileName) {
      this.fileName = fileName;
    }
    if (time) {
      this.nextDate = Number(time);
    }
    this.getAreas();
    setTimeout(() => {
      this.getList();
    }, 1000);
  },

  computed: {
    ...mapState(["areas", "isTanma", "errorList"]),
    areaComputed() {
      return (value) => {
        if (this.$store.state.areas) {
          const item = this.$store.state.areas.find(
            (item) => item.id === value
          );
          return item ? item.name : "";
        }
        return this.$store.state.areas;
      };
    },

    areasFilter() {
      let data = [];
      let obj = {};
      this.areas.length &&
        this.areas.forEach((item) => {
          obj = {
            text: item.name,
            value: item.id,
          };
          data.push(obj);
        });

      return data;
    },

    filterClientTime() {
      return (list, time) => {
        let num = [];
        num = list.filter((item) => {
          let t = item.time.split(":")[0] * 1 < 12 ? "AM" : "PM";
          return t === time;
        });
        return num;
      };
    },
    filterStaffTime() {
      return (list = [], time, date = new Date().getTime(), list1 = []) => {
        if (!list.length || !list1.length || !time || !date) return [];
        const startDay = new Date(date);
        const noonDay = new Date(date);
        const endDay = new Date(date);

        startDay.setHours(9, 0, 0, 0);
        noonDay.setHours(12, 0, 0, 0);
        endDay.setHours(18, 0, 0, 0);
        let num = [];
        num = list.filter((item) => {
          // 过滤掉不包含的职责
          if (!list1.some((i) => i.type === item.post)) return false;

          // 过滤不在客户地区范围内的员工
          // if (
          //   !list1.some(
          //     (i) => i.areaId === item.areaId && i.cityId === item.cityId
          //   )
          // )
          //   return false;

          if (list1.some((i) => i.userId === item.id)) return false;

          if (time === "AM") {
            if (
              item.leaveStart === 0 ||
              item.leaveEnd === 0 ||
              item.leaveStart === null ||
              item.leaveEnd == null ||
              item.leaveEnd * 1000 <= startDay ||
              item.leaveStart * 1000 >= noonDay
            )
              return true;

            return false;
          }

          if (time === "PM") {
            if (
              item.newPeople === 1 &&
              item.leaveEnd * 1000 >= startDay &&
              item.leaveEnd * 1000 <= noonDay
            )
              return true;

            if (item.newPeople === 1) return false;

            if (
              item.leaveStart === 0 ||
              item.leaveEnd === 0 ||
              item.leaveStart === null ||
              item.leaveEnd == null ||
              item.leaveEnd * 1000 <= noonDay ||
              item.leaveStart * 1000 > endDay
            )
              return true;

            return false;
          }

          return false;
        });
        return num;
      };
    },
  },

  watch: {
    selectProductCateValue: function (newValue) {
      if (newValue != null && newValue.length == 2) {
        this.listQuery.productCategoryId = newValue[1];
      } else {
        this.listQuery.productCategoryId = null;
      }
    },
    dialogVisible(val) {
      this.dialogVisible = val;
    },
  },

  methods: {
    /**
     * 过滤数据
     * @param {{}} data
     */
    filterClient(data) {
      this.fliterVisit = data;
    },

    filterSecond(data) {
      this.fliterVisitSecond = data;
    },

    deleteClientByAfternoon() {
      this.commonDel(this.fliterVisitSecond, this.clientPM);

      this.clientPMLength = this.clientPM.length;

      this.list2 = this.clientAM;
    },

    deleteClient() {

      console.log("this.fliterVisit", this.fliterVisit, "this.clientAM", this.clientAM);
      
      this.commonDel(this.fliterVisit, this.clientAM);

      this.list1 = this.clientAM;

      this.clientAMLength = this.clientAM.length;
    },

    /**
     *
     * @param {[]} fileList  要过滤的
     * @param {[]} client  客户列表
     */
    commonDel(fileList, client) {
      let json = {};
      let params = [];
      for (let index = 0; index < fileList.length; index++) {
        const element = fileList[index];

        json[element.id] = element.id;

        params[index] = element.id;
      }

      console.log("json", json, "client", client);

      // let resultData = [];
      for (let index = 0; index < client.length; index++) {
        const element = client[index];
        console.log("element", element);
        if (!json.hasOwnProperty(element.id)) {
          continue;
        }
        console.log("index", index);
        client.splice(index, 1);
        index--;
      }

      console.log("client", client);

      removeClient({ id: params });
    },

    /**
     * 查看错误列表
     */
    lookErrorList() {
      this.showErrorClient = true;
    },

    closeErrorPage() {
      this.showErrorClient = false;
    },

    change1(val) {
      this.submitParams.ids = val;
    },
    change2(val) {
      this.submitParams.afternoons = val;
    },
    // 地区信息
    getAreas() {
      getArea({
        id: 0,
      }).then((response) => {
        if (response.data && response.data.length) {
          this.$store.commit("SET_AREAS", response.data);
        }
      });
    },

    postFilter1(value, row) {
      return row.post === value;
    },
    areasFilters(value, row) {
      return row.areaId === value;
    },
    clearFilter() {
      this.$refs.clientTable1.clearFilter();
      this.$refs.staffTable1.clearFilter();
      this.$refs.clientTable2.clearFilter();
      this.$refs.staffTable2.clearFilter();
    },

    postFilter(value, row) {
      console.log("value", value, "row", row);
      return row.type === value;
    },

    filterMethod(value, row) {
      let t = row.time.split(":")[0] * 1 < 12 ? "AM" : "PM";
      return t === value;
    },
    filterHandler(value, row) {
      return row.userName === value;
    },

    handleCurrentChange,
    handleSelectionChange,
    handleSizeChange,

    handleMint(index, row) {
      mint({ id: [row.id] }).then((res) => {
        Message({
          message: res.data.message,
          duration: 3 * 1000,
        });

        this.list[index].mintStatus = 1;
      });
    },

    closeDialog(value) {
      this.$set(this, "dialogVisible", value);
    },
    /**
     * 树形菜单选择
     */
    currentChangeHandle(data) {
      this.currentNftType = data.label;
      this.nftTypeId = data.value;
      this.listQuery.nftType = data.value;
    },

    getProductSkuSp(row, index) {
      let spData = JSON.parse(row.spData);
      if (spData != null && index < spData.length) {
        return spData[index].value;
      } else {
        return null;
      }
    },

    getResponse(response) {
      this.listLoading = false;
      this.list = response.data;
      this.list.forEach((item) => {
        item.undertakingTime = FormatCreateTime(item.undertakingTime);
        item.createTime = FormatCreateTime(item.createTime);
      });

      this.total = response.total;
      this.size = response.pageSize;
      Storage.marketnftByStorage(this.list);
    },

    async getList() {
      this.celientListLoading = true;
      this.staffListLoading = true;
      await this.getClientList();
      await this.getStaffList();

      await getErrorListByRequest(this);

    },

    getClientList() {
      return clientList({ pageNum: this.clientParams.pageNum }).then((res) => {
        if (this.clientParams.pageNum === 1) {
          this.list1 = [];
        }
        this.clientParams.pageSize = res.data.pageSize;
        this.clientParams.total = res.data.total;
        this.list1 = this.list1.concat(res.data.data);




        const totalPage = Math.ceil(res.data.total / res.data.pageSize);
        if (this.clientParams.pageNum < totalPage) {
          this.clientParams.pageNum++;
          this.getClientList();
        } else {
          let client
          this.clientAM = this.filterClientTime(this.list1, "AM");

          this.parseFrontPlus(this.clientAM);

          this.clientPM = this.filterClientTime(this.list1, "PM");

          this.parseFrontPlus(this.clientPM);
          this.clientAMLength = this.clientAM.length;
          this.clientPMLength = this.clientPM.length;
          this.celientListLoading = false;
        }
      });
    },

    parseFrontPlus(data = []) {
      
      for (let i = 0; i < data.length; i++) {

        if (2 != data[i].type) {
          break;
        }

        data[i].type = 0;
      }
    },
    

    getStaffList() {
      if (this.staffParams.pageNum === 1) {
        this.list2 = [];
        this.staffParams.lastId = 0;
      } else {
        this.staffParams.lastId = maxNum(this.list2, "id");
      }

      let citys = localStorage.getItem("cityOptions");

      if (!citys) {
        return; 
      }

     

      let param = sessionStorage.getItem("tanma");

      if (!param) {
        return; 
      }

      let paramObj = JSON.parse(param);

      let cityList =  JSON.parse(citys);

      let citysParam = [];

      for (let i = 0; i < paramObj.city.length; i++) {

        citysParam.push(cityList.options[paramObj.city[i]].name);

      }

      console.log("citysParam", citysParam)
      


      return staffListSearch({
        pageNum: this.staffParams.pageNum,
        cityName: citysParam,
        lastId: this.staffParams.lastId,
      }).then((res) => {
        this.staffParams.pageSize = res.data.pageSize;
        this.staffParams.total = res.data.total;
        this.list2 = this.list2.concat(res.data.data);
        const totalPage = Math.ceil(res.data.total / res.data.pageSize);
        if (this.staffParams.pageNum < totalPage) {
          this.staffParams.pageNum++;
          this.getStaffList();
        } else {
          setTimeout(() => {
            this.list2 = this.filterEmployeess(
              this.list2,
              this.isTanma
                ? this.nextDate
                : this.list1.length
                ? this.list1[0].day * 1000
                : null
            );
            this.list3 = this.filterStaffTime(
              this.list2,
              "AM",
              this.isTanma
                ? this.nextDate
                : this.list1.length
                ? this.list1[0].day * 1000
                : null,
              this.clientAM
            );
            this.list4 = this.filterStaffTime(
              this.list2,
              "PM",
              this.isTanma
                ? this.nextDate
                : this.list1.length
                ? this.list1[0].day * 1000
                : null,
              this.clientPM
            );
          }, 0);
          this.staffListLoading = false;
        }
      });
    },

    getBrandList() {
      fetchBrandList({ pageNum: 1, pageSize: 100 }).then((response) => {
        this.brandOptions = [];
        let brandList = response.data.data;
        for (let i = 0; i < brandList.length; i++) {
          this.brandOptions.push({
            label: brandList[i].name,
            value: brandList[i].id,
          });
        }
      });
    },

    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getListBySearch();
    },

    getListBySearch() {
      listBySearch(this.listQuery).then((r) => this.getResponse(r));
    },
    handleAddProduct() {
      this.$router.push({ path: "/certificate/addProduct" });
    },
    handleBatchOperate() {
      if (this.operateType == null) {
        this.$message({
          message: "请选择操作类型",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      if (this.multipleSelection == null || this.multipleSelection.length < 1) {
        this.$message({
          message: "请选择要操作的证书",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      this.$confirm("是否要进行该批量操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ids = [];

        console.log(this.multipleSelection);
        let map = {};
        for (let i = 0; i < this.multipleSelection.length; i++) {
          map[this.multipleSelection[i].id] = this.multipleSelection[i];
          ids.push(this.multipleSelection[i].id);
        }

        this.operateType.call(ids).then((res) => {
          for (let i = 0; i < this.list.length; i++) {
            if (map[this.list[i].id]) {
              this.list[i][this.operateType.key] = this.operateType.value;
            }
          }
        });
      });
    },

    handlePublishStatusChange(index, row) {
      let ids = [];
      ids.push(row.id);
      this.updatePublishStatus(row.status, ids);
    },
    handleNewStatusChange(index, row) {
      let ids = [];
      ids.push(row.mid);
      updateHot(row.hot, ids);
    },
    handleRecommendStatusChange(index, row) {
      let ids = [];
      ids.push(row.id);
      this.updateRecommendStatus(row.recommandStatus, ids);
    },
    handleResetSearch() {
      this.selectProductCateValue = [];
      this.listQuery = Object.assign({}, this.defaultListQuery);
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleDelete(index, row) {
      this.$confirm("是否要进行删除操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ids = [];
        ids.push(row.id);
        this.updateDeleteStatus(1, ids);
      });
    },
    handleUpdateProduct(index, row) {
      this.$router.push({
        path: "/certificate/updateProduct",
        query: { id: row.id },
      });
    },
    handleShowProduct(index, row) {
      this.dialogVisible = true;
      console.log(row);
      this.$refs.listByProductDetails.pullData(row.mid);
    },
    handleShowVerifyDetail(index, row) {
      console.log("handleShowVerifyDetail", row);
    },
    handleShowLog(index, row) {
      console.log("handleShowLog", row);
    },
    updatePublishStatus(publishStatus, ids) {
      let params = {
        ids: ids,
        status: publishStatus,
      };
      updateStatus(params).then((response) => {
        this.$message({
          message: "修改成功",
          type: "success",
          duration: 1000,
        });
      });
    },
    updateNewStatus(newStatus, ids) {
      let params = new URLSearchParams();
      params.append("ids", ids);
      params.append("newStatus", newStatus);
      updateNewStatus(params).then((response) => {
        this.$message({
          message: "修改成功",
          type: "success",
          duration: 1000,
        });
      });
    },
    updateRecommendStatus(recommendStatus, ids) {
      let params = new URLSearchParams();
      params.append("ids", ids);
      params.append("recommendStatus", recommendStatus);
      updateRecommendStatus(params).then((response) => {
        this.$message({
          message: "修改成功",
          type: "success",
          duration: 1000,
        });
      });
    },
    updateDeleteStatus(deleteStatus, ids) {
      let params = new URLSearchParams();
      params.append("ids", ids);
      params.append("deleteStatus", deleteStatus);
      updateDeleteStatus(params).then((response) => {
        this.$message({
          message: "删除成功",
          type: "success",
          duration: 1000,
        });
      });
      this.getList();
    },
    // 过滤派单人员
    filterEmployeess(employee, date = new Date().getTime()) {
      if (!employee.length) return "";
      const dayStart = new Date(date);
      const dayEnd = new Date(date);
      dayStart.setHours(9, 0, 0, 0);
      dayEnd.setHours(18, 0, 0, 0);

      return employee.filter((item) => {
        // 保留包含明天时间段或明天上午/下午的员工
        // 过滤离职员工
        if (item.depart === 0) return false;
        if (
          item.leaveEnd * 1000 <= dayStart ||
          (item.leaveStart * 1000 <= dayStart &&
            item.leaveEnd * 1000 < dayEnd) ||
          (item.leaveStart * 1000 >= dayStart &&
            item.leaveEnd * 1000 < dayEnd) ||
          item.leaveStart * 1000 > dayEnd ||
          (item.leaveEnd === 0 && item.leaveStart === 0) ||
          (item.leaveEnd === null && item.leaveStart === null)
        )
          return true;

        // 其他情况过滤掉
        return false;
      });
    },

    getGenreateResult() {
      if (!this.list1.length) {
        Message.error("没有客户可派单");
        return false;
      }
      this.btnLoading = true;
      let params = {
        ids: [],
        afternoons: [],
        pageNum: 1,
      };
      this.submitParams.ids.length &&
        this.submitParams.ids.forEach((item) => {
          params.ids.push(item.id);
        });
      this.submitParams.afternoons.length &&
        this.submitParams.afternoons.forEach((item) => {
          params.afternoons.push(item.id);
        });

      let listLength1 = this.filterClientTime(this.list1, "AM");
      let listLength2 = this.filterClientTime(this.list1, "PM");
      const count1 = listLength1.filter((obj) => obj.userName !== null).length;
      const count2 = listLength2.filter((obj) => obj.userName !== null).length;
      if (
        listLength1.length &&
        params.ids.length + count1 < listLength1.length
      ) {
        Message.error("上午派单人数异常");
        this.btnLoading = false;
        return false;
      }
      // if (
      //   0 == listLength2.length
      // ) {
      //   Message.error("下午派单人数异常");
      //   this.btnLoading = false;
      //   return false;
      // }

      let index = (listLength1.length + listLength2.length) / 10, waitTime = 0;
      
      index = Math.floor(index);

      if (index < 6) {
        waitTime = WAIT_TIME[index];
      } else {
        waitTime = 20000;
      }
      console.log("waitTime", waitTime);

      genreateResult(params)
        .then((res) => {
          this.countdown = waitTime / 1000;
          this.interval = setInterval(() => {
            this.countdown--;
          }, 1000);
          this.timer = setTimeout(() => {
            clearInterval(this.interval);
            this.interval = null;
            clearTimeout(this.timer);
            this.timer = null;
            if (this.isTanma) {
              this.$router.push({
                path: "/dispatch/audit",
                query: {
                  fileName: "探马获取",
                  time: this.nextDate,
                },
              });
            } else {
              this.$router.push({
                path: "/dispatch/audit",
              });
            }
            this.btnLoading = false;
          }, waitTime);
        })
        .catch((error) => {
          this.btnLoading = false;
        });
    },
  },
  beforeDestroy() {
    clearInterval(this.interval);
    this.interval = null;
    clearTimeout(this.timer);
    this.timer = null;
  },
};
</script>
<style>
.el-tabs {
  width: 100%;
}
.table-container {
  display: flex;
  flex: auto;
}
.el-tab-pane {
  display: flex;
}
.el-table {
  height: max-content !important;
}
.btn-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  margin-top: 25px;
}

.btn-container-del {
  display: -webkit-box;
  display: -ms-flexbox;
  /* display: flex; */
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  margin-top: 1%;
  position: relative;
  /* left: -15%; */
  margin-left: -5%;
  width: 2%;
}
.btn {
  width: 260px;
  height: 40px;
  font-size: 16px;
  letter-spacing: 2px;
}
</style>


